﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using StyleMVVM.ViewModel;

namespace StyleMVVM.View
{
    /// <summary>
    /// This is the base page that all templates are based off
    /// </summary>
    public class BasePhoneApplicationPage : PhoneApplicationPage
    {
        /// <summary>
        /// Holds reference to injected INavigationViewModel
        /// </summary>
        private INavigationViewModel CurrentViewModel { get; set; }

        public BasePhoneApplicationPage()
        {

            Binding b = new Binding("DataContext") { Source = this };
            var prop = System.Windows.DependencyProperty.RegisterAttached(
                        "ListenDataContext",
                        typeof(object),
                        typeof(BasePhoneApplicationPage),
                        new System.Windows.PropertyMetadata(ListenDataContextPropertyChanged));
            this.SetBinding(prop, b);
        }

        /// <summary>
        /// Method raised when DataContext changed. 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void ListenDataContextPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            BasePhoneApplicationPage currentview = sender as BasePhoneApplicationPage;

            var viewModel = currentview.DataContext as INavigationViewModel;

            if (viewModel != null)
            {
                currentview.CurrentViewModel = viewModel;
            }
        }

        protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
        {
            base.OnNavigatingFrom(e);

            if (CurrentViewModel != null)
                CurrentViewModel.NavigatingFrom(this, new StyleNavigatingCancelEventArgs(e));
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (CurrentViewModel != null)
            {
                CurrentViewModel.NavigatedTo(this,new StyleNavigationEventArgs(e));
            }
            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);

            if (CurrentViewModel != null)
            {
                CurrentViewModel.NavigatedFrom(this, new StyleNavigationEventArgs(e));
            }
        }
    }
}
